<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Http\Models\Post;
use App\Http\Models\PostCid;

class PostController extends AdminBaseController {

    public function __construct(Request $request){
        parent::__construct($request);
        $this->param['active'] = 'post';
    }

    public function index(Request $request,$type)
    {
        if(!isset($type)) $type = 1;
        //data不可数
        $data = Post::where("status",$type)->orderBy("created_at","desc");
        $data = $data->paginate(5);

        $cids = PostCid::all();

        $cidsArr = [0=>'未分类'];
        foreach($cids as $key => $val ){
            $cidsArr[$val->id] = $val->title;
        }


        $this->param['data'] = $data;
        $this->param['cids'] = $cidsArr;
        $this->param['type'] = $type;

        return view("admin.post.index",$this->param);
    }

    public function create(Request $request)
    {
        $cids = PostCid::all();

        $this->param['cids'] = $cids;

        return view('admin.post.create',$this->param);
    }

    public function store(Request $request){
        $post = new Post;
        $post -> title = $request->input('title');
        $post -> cid = $request -> input('cid');//文章的分类
        $post -> cover = $request ->input('cover');
        $post -> description   = $request -> input('description');
        $post -> content = $request -> input('content');
        $post -> save();
        return redirect('/administrator/0/post');
    }

    public function edit($id){

        $post = Post::find($id);

        $cids = PostCid::all();

        $this->param['cids'] = $cids;
        $this->param['post'] = $post;

        return view('admin.post.edit',$this->param);
    }


    public function update(Request $request,$id)
    {

        $this->validate($request,[
            "title"=>'sometimes',
            'content'=>'sometimes',
            'cid'=>'sometimes',
            'cover'=>'sometimes',
            'description'=>'sometimes',
        ]);

        Post::where("id",$id)->update($request->all());

        if($request->ajax()){
            return response()->json(["state"=>"ok","message"=>"操作成功"]);
        }

        return redirect('/administrator/0/post');
    }



    public function delete($id)
    {
        $res = Post::destroy($id);
        if($res) return view('success',['url'=>'/administrator/post']);

        return view('failure',['url'=>'/administrator/1/post']);
    }


}
